/*************************************************************************
    > File Name: tcpcli.c
    > Author: Xing.Dai
    > Mail: Xing.Dai@aliyun.com 
    > Created Time: 2017-04-01 00:05
 ************************************************************************/


#include "common.h"



int main(int argc, char **argv)
{
	int sockfd;
	struct sockaddr_in srvaddr;

	int maxfdp1;
	fd_set rset;
	char buf[MAXLINE];
	int n = 0;
	int tx_buf;
	int ret = 0;

	time_t now;
	struct tm *local;

	time(&now);
	local = localtime(&now);
	tx_buf = local->tm_sec;
	// printf("current: %d\r\n", tx_buf);
	// return 0;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("Client socket failed. %d\r\n", sockfd);
		return -1;
	}
	bzero(&srvaddr, sizeof(struct sockaddr_in));
	srvaddr.sin_family = AF_INET;
	srvaddr.sin_port = htons(SERVER_PORT);
	inet_pton(AF_INET, SERVER_IP, &srvaddr.sin_addr);
	if ((ret = connect(sockfd, (struct sockaddr *)&srvaddr, sizeof(srvaddr))) < 0) {
		printf("Client connect failed. %d\r\n", ret);
		return -1;
	}
	if ((send(sockfd, (void *)&tx_buf, 4, 0)) < 0) {
		printf("Client write socket %d failed. \r\n", sockfd);
		return -1;
	}
	printf("write to socket success.\r\n");

	FD_ZERO(&rset);

	while(1) {
		FD_SET(sockfd, &rset);
		maxfdp1 = sockfd + 1;
		select(maxfdp1, &rset, NULL, NULL, NULL);
		if (FD_ISSET(sockfd, &rset)) {
			if ((n = recv(sockfd, buf, MAXLINE, 0)) == 0) {
				printf("Server terminated prematurely\r\n");
				return 0;
			}
			printf("receive %d bytes. %d\r\n", (int)n, (int)buf[0]);
		}
	}

	return 0;
}
